﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpAlgorithm
{
    class JobList
    {
        public JobList()
        {
            int C = GetConsole.GetInt();
            List<JobNode> jobList = new List<JobNode>();
            while (C-- > 0)
            {
                int N = GetConsole.GetInt();
                for (int i = 0; i < N; i++)
                {
                    char alphabet = (char)('A' + i);
                    jobList.Add(new JobNode(alphabet.ToString()));
                }
                int M = GetConsole.GetInt();
                for (int i = 0; i < M; i++)
                {
                    string jobOrder = GetConsole.GetString().ToUpper();

                    JobNode beforeJob = jobList.Find(j => j.id == jobOrder[0].ToString());
                    JobNode nextJob = jobList.Find(j => j.id == jobOrder[1].ToString());
                    beforeJob.AddNextNode(nextJob);
                    nextJob.AddBeforeNode(beforeJob);

                }
                List<JobNode> findJobList = jobList.FindAll(j => j.beforeJobCount == 0).OrderBy(j => j.id).ToList();
                while (findJobList.Count > 0)
                {
                    Console.Write(findJobList[0].id);
                    foreach (JobNode node in findJobList[0].nextJobList)
                    {
                        node.beforJobList.Remove(findJobList[0]);
                    }
                    jobList.Remove(findJobList[0]);
                    findJobList = jobList.FindAll(j => j.beforeJobCount == 0).OrderBy(j => j.id).ToList();
                }
                Console.Write("\n");
            }
        }
    }
    class JobNode
    {
        public string id = string.Empty;
        public List<JobNode> beforJobList = new List<JobNode>();
        public List<JobNode> nextJobList = new List<JobNode>();
        public int beforeJobCount
        {
            get { return beforJobList.Count; }
        }
        public JobNode(string id)
        {
            this.id = id;
        }
        public void AddBeforeNode(JobNode node)
        {
            if (!beforJobList.Contains(node))
            {
                beforJobList.Add(node);
                if (beforJobList.Count > 1)
                { beforJobList.OrderBy(p => p.id); }
            }
        }
        public void AddNextNode(JobNode node)
        {
            if (!nextJobList.Contains(node))
            {
                nextJobList.Add(node);
                if (nextJobList.Count > 1)
                { nextJobList.OrderBy(p => p.id); }
            }
        }
    }
}
